﻿using Infrastructure.Lib.Core;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RecognitionForm
{
    public static class WriteTxtExt
    {
        public static object @lock = new object();

        public static string SavePath = ConfigHelper.GetAppSetting("SavePath");

        public static string SaveFileName = ConfigHelper.GetAppSetting("SaveFileName");

        public static void WriteTxtLock(this string txt, FileMode mode = FileMode.Append)
        {
            lock (@lock)
            {
                if (!System.IO.Directory.Exists(SavePath))
                    System.IO.Directory.CreateDirectory(SavePath);

                var fileName = Path.Combine(SavePath, SaveFileName);

                StringBuilder sb = new StringBuilder();
                sb.AppendLine(txt);

                if (!System.IO.File.Exists(fileName))
                    System.IO.File.Create(fileName).Close();

                if (string.IsNullOrEmpty(txt))
                {
                    using (FileStream fileStream = new System.IO.FileStream(fileName, FileMode.Create, FileAccess.Write))
                    {
                    }
                }
                else
                {

                    using (FileStream fileStream = new System.IO.FileStream(fileName, mode, FileAccess.Write))
                    using (StreamWriter sw = new System.IO.StreamWriter(fileStream, Encoding.UTF8))
                    {
                        sw.Write(sb.ToString());
                    }
                }
            }
        }
    }
}
